package com.raos.example.memory.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import jakarta.persistence.*;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 会话消息实体类
 *
 * @author raos
 * @date 2025-07-12 16:11
 */
@Data
@Table(name = "ai_chat_message", indexes = {
        @Index(name = "messageId_chat_index", columnList = "chatMemoryId")
})
@Entity(name = "AI会话-会话消息")
public class MyChatMessage {

    /**
     * 数据库主键ID
     */
    @Id
    @Column(columnDefinition = "varchar(64) NOT NULL COMMENT '消息ID'")
    private String messageId;

    /**
     * 会话ID
     */
    @Column(columnDefinition = "varchar(64) DEFAULT NULL COMMENT '会话ID'")
    private String chatMemoryId;

    /**
     * 会话内容
     */
    @Column(columnDefinition = "text DEFAULT NULL COMMENT '会话内容'")
    private String content;

    /**
     * 消息类型
     */
    @Column(columnDefinition = "varchar(32) DEFAULT NULL COMMENT '消息类型'")
    private String messageType;

    /**
     * 添加时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(columnDefinition = "datetime DEFAULT NULL COMMENT '添加时间'")
    private LocalDateTime addTime;

    @PrePersist
    public void preSave() {
        this.addTime = LocalDateTime.now();
    }


    /**
     * 创建一个会话消息对象
     *
     * @param memoryId 会话ID
     * @param messageType 消息类型
     * @param message 消息内容
     * @return 会话消息对象
     */
    public static MyChatMessage create(String memoryId, String messageType, String message) {
        MyChatMessage chatMessage = new MyChatMessage();
        chatMessage.setMessageId(UUID.randomUUID().toString());
        chatMessage.setChatMemoryId(memoryId);
        chatMessage.setMessageType(messageType);
        chatMessage.setContent(message);
        return chatMessage;
    }

    /**
     * 将数据库实体消息对象 转换为 ChatMessage 类型消息
     */
    public ChatMessage toChatMessage() {
        if ("SYSTEM".equals(this.messageType)) {
            return new UserMessage(this.content);
        }
        else if ("USER".equals(this.messageType)) {
            return new UserMessage(this.content);
        }
        else if ("AI".equals(this.messageType)) {
            return new AiMessage(this.content);
        }
        else if ("TOOL_EXECUTION_RESULT".equals(this.messageType)) {
            return new AiMessage(this.content);
        } else if ("CUSTOM".equals(this.messageType)) {
            return new AiMessage(this.content);
        }
        return null;
    }

}
